<?php
namespace app\api\controller;
use think\Controller;
use Util\Sysdb;
class Common extends Controller
{
    //控制器初始化方法
    public function _initialize()
    {
        /** 项目的根目录文件目录地址 */
        define('DOCUMENT_ROOT', dirname(realpath(dirname(__FILE__))));
    }
    public function writeLog ($content,$filename='')
    {
        $logFileDir = DOCUMENT_ROOT.'/Log';
        if (!is_dir($logFileDir)){
            mkdir($logFileDir,0777,true);
        }
        $path = $logFileDir.'/'.$filename;

        if (!is_dir($path)){
            mkdir($path,0777,true);
        }
        $file = $path.'/'.date('Y_m_d').'_'.$filename.'.txt';
        file_put_contents($file,$content.PHP_EOL,FILE_APPEND);  // 最简单的快速的以追加的方式写入写入方法，
    }
    /**
     * @param $url
     * @param $data
     * @param string $method
     * @param string $type
     * @return bool|string
     */
    function curlData($url,$data,$method = 'GET',$type='json')
    {
        //初始化
        $ch = curl_init();
        $headers = [
            'form-data' => ['Content-Type: multipart/form-data'],
            'json'      => ['Content-Type: application/json'],
        ];
        if($method == 'GET'){
            if($data){
                $querystring = http_build_query($data);
                $url = $url.'?'.$querystring;
            }
        }
        // 请求头，可以传数组
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_HTTPHEADER,$headers[$type]);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);         // 执行后不直接打印出来
        if($method == 'POST'){
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST,'POST');     // 请求方式
            curl_setopt($ch, CURLOPT_POST, true);               // post提交
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);              // post的变量
        }
        if($method == 'PUT'){
            curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "PUT");
            curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
        }
        if($method == 'DELETE'){
            curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
            curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
        }
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 不从证书中检查SSL加密算法是否存在
        $output = curl_exec($ch); //执行并获取HTML文档内容
        curl_close($ch); //释放curl句柄
        return $output;
    }
    /**
     * 对象 转 数组
     *
     * @param object $obj 对象
     * @return array
     */
    function object_to_array($obj) {
        $obj = (array)$obj;
        foreach ($obj as $k => $v) {
            if (gettype($v) == 'resource') {
                return;
            }
            if (gettype($v) == 'object' || gettype($v) == 'array') {
                $obj[$k] = (array)object_to_array($v);
            }
        }
        return $obj;
    }
}